package zmee.pmbs.formplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.pmgt.pmbs.common.enums.BudgetSourceTypeEnum;
import kd.pmgt.pmbs.common.enums.StatusEnum;
import kd.pmgt.pmbs.formplugin.OutBudgetPerformMonitorFormPlugin;
import zmee.common.allhelper.OccupiedAmountCalculateHelper;
import zmee.entity.BudgetProInfo;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author yss
 * @createTime 2022-12-09 14:37
 * @description 项目支出预算执行列表扩展
 */
public class ProjectBudgetperformExtListPlugin extends OutBudgetPerformMonitorFormPlugin {

    protected void loadData(List<QFilter> qFilters) {
        Integer periodYear = periodYear(qFilters);
        this.getModel().deleteEntryData("performbillentry");
        this.getView().setVisible(Boolean.FALSE, new String[]{"contperformentry", "performbillentry"});
        this.getModel().deleteEntryData("budgetentry");
        String payDirection = (String)this.getView().getFormShowParameter().getCustomParam("paydirection");
        if (payDirection != null) {
            this.getPageCache().put("payDirection", payDirection);
        }

        if (!qFilters.isEmpty()) {
            DynamicObjectCollection budgetEntryEntity = this.getModel().getEntryEntity("budgetentry");
            String cpName = this.getPageCache().get("filftername");
            if (cpName.equals("=")) {
                qFilters.add(new QFilter("sourcetype", "=", BudgetSourceTypeEnum.OUT.getValue()));
                DynamicObject[] budgets = BusinessDataServiceHelper.load("pmas_projectbudgetperform", "name, description, siamount, viamount, budgetamount, vichangeamount, budgetitem, sourcetype, project, parent, currency, sequence, remindrate, controlrate, remainrate, remindamt, controlamt, preoccupyamt, occupyamt, performamt, remainamt, contcurrency, org, contractcurrency,actualamt,procostamt,billtype,billamt,billstatus,performamttype,yearbudgetrecord,yearbudgetrecord.year,yearbudgetrecord.lastyearsurplusamt,yearbudgetrecord.lastyearsurplusamt,", (QFilter[])qFilters.toArray(new QFilter[qFilters.size()]), "sequence asc");
                String projectId = this.getPageCache().get("projectfilterid");
                DynamicObject project = BusinessDataServiceHelper.loadSingle("bd_project", "id,name", new QFilter[]{new QFilter("id", "=", Long.parseLong(projectId))});
                Map<Object, BigDecimal> budgetToCostAmtMap = new HashMap(16);
                if (project != null) {
                    QFilter statusFilter = new QFilter("billstatus", "=", StatusEnum.CHECKED.getValue());
                    QFilter proFilter = new QFilter("project", "=", Long.parseLong(projectId));
                    DynamicObject[] contractCostObjs = BusinessDataServiceHelper.load("pmco_contractcost", "entryentity,subentryentity,budgetitem,amount,currency", new QFilter[]{statusFilter, proFilter});
                    this.fillBudgetCostAmtMap(contractCostObjs, budgetToCostAmtMap);
                }

                if (budgets != null && budgets.length > 0) {
                    DynamicObject firstRow = this.buildTotalRow(budgetEntryEntity);
                    budgetEntryEntity.add(firstRow);
                    DynamicObject[] totalBudgets = this.findAllBudgets(budgets, (Set)null);
                    Set<Long> parentIdSet = this.getAllParents(totalBudgets);
                    DynamicObjectType dt = budgetEntryEntity.getDynamicObjectType();
                    DynamicObject[] var13 = budgets;
                    int var14 = budgets.length;

                    for(int var15 = 0; var15 < var14; ++var15) {
                        DynamicObject budget = var13[var15];
                        budgetEntryEntity.add(this.buildBudgetEntry(budget, dt, parentIdSet, budgetToCostAmtMap));
                    }

                    firstRow.set("budgetcurrency", ((DynamicObject)budgetEntryEntity.get(1)).get("budgetcurrency"));
                }

                this.mergeBudgetEntryDataToRow(budgetEntryEntity);
                this.fillStatisticRegionValue();
                this.setEntryYearOcc(periodYear,budgetEntryEntity);
                this.getModel().updateEntryCache(budgetEntryEntity);
            }
        }

        this.getView().updateView("budgetentry");
    }

    /**
     * 获取期间年份
     * @param qFilters
     * @return
     */
    protected Integer periodYear(List<QFilter> qFilters){
        Integer periodYear = 0;
        Long periodId = 0L;
        Iterator<QFilter> iterator = qFilters.iterator();
        while (iterator.hasNext()){
            QFilter next = iterator.next();
            if("zmee_period.id".equals(next.getProperty())){
                periodId = Long.valueOf(String.valueOf(next.getValue()));
                iterator.remove();
            }
        }
        DynamicObject periodDy = BusinessDataServiceHelper.loadSingleFromCache(periodId, "bd_period", "periodyear");
        if(periodDy != null){
            periodYear = periodDy.getInt("periodyear");
        }
        return periodYear;
    }

    /**
     * 设置年度已占用
     * @param year
     * @param budgetEntryEntity
     */
    protected void setEntryYearOcc(Integer year, DynamicObjectCollection budgetEntryEntity){//zmee_yearamt
        String projectIdStr = this.getPageCache().get("projectfilterid");
        Long projectId = Long.valueOf(projectIdStr);
        BudgetProInfo budgetProInfo = new BudgetProInfo(projectId);
        Map<Long, Map<Integer, BigDecimal>> occupiedAmountMap = OccupiedAmountCalculateHelper.calculateOccupiedBudgetitemAmount(projectId,true,budgetProInfo);
        Map<Long, Map<Integer, BigDecimal>> proPayAmountMap = OccupiedAmountCalculateHelper.calculateProPayAmt(projectId,true,budgetProInfo);
        Map<Long, Map<Integer, BigDecimal>> budgetAmountMap = OccupiedAmountCalculateHelper.calculateBudgetAmt(projectId,true,budgetProInfo);
        for (DynamicObject budgetEntryDy : budgetEntryEntity) {
            //获取预算项信息
            long projectBudgetPerFormId = budgetEntryDy.getLong("id");
            //获取预算项生效id
            Long budgetValidId = budgetProInfo.getBudgetValidId(projectBudgetPerFormId, true, year);
            Map<Integer, BigDecimal> bugGetAmtMap = occupiedAmountMap.get(budgetValidId);
            Map<Integer, BigDecimal> proPayAmtMap = proPayAmountMap.get(budgetValidId);
            Map<Integer, BigDecimal> budgetAmtMap = budgetAmountMap.get(budgetValidId);
            BigDecimal budgetYearAmt = BigDecimal.ZERO;
            BigDecimal payYearAmt = BigDecimal.ZERO;
            BigDecimal budgetAmt = BigDecimal.ZERO;
            if(bugGetAmtMap != null){
                budgetYearAmt = bugGetAmtMap.get(year);
            }
            if(proPayAmtMap != null){
                payYearAmt = proPayAmtMap.get(year);
            }
            if(budgetAmtMap != null){
                budgetAmt = budgetAmtMap.get(year);
            }
            budgetEntryDy.set("zmee_yearamt",budgetYearAmt);
            budgetEntryDy.set("zmee_yearpayamt",payYearAmt);
            budgetEntryDy.set("zmee_yearbudgetamt",budgetAmt);
        }
    }
}
